<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/10/14
 * Time: 13:09
 */

namespace Home\Controller;
use Think\Controller;
use Think\Model;
use Home\Model\TicketModel;
use Home\Model\UserModel;
class PayController extends  Controller {

     protected $private_key;
    protected  $public_key;

    public function __Construct()
    {
//        $this->private_key = 'D:\WWW\svnwelove\Application\Common\Conf\rsa_private_key.pem';//windows本地的配置路径
//        $this->public_key = 'D:\WWW\svnwelove\Application\Common\Conf\rsa_public_key.pem';//windows本地的配置路径
//
//        $this->private_key = 'D:\WWW\svnwelove\Application\Common\Conf\s_rsa_private_key.pem';//windows本地的配置路径
//        $this->public_key = 'D:\WWW\svnwelove\Application\Common\Conf\s_rsa_public_key.pem';//windows本地的配置路径
//
//        $this->private_key = '/alidata/www/default/we_love/Application/Common/Conf/s_rsa_private_key.pem';//linux服务器上的配置路径
//        $this->public_key = '/alidata/www/default/we_love/Application/Common/Conf/s_rsa_public_key.pem'; //linux服务器上的配置路径
//
        $this->private_key = '/alidata/www/default/we_love/Application/Common/Conf/rsa_private_key.pem';//linux服务器上的配置路径
        $this->public_key = '/alidata/www/default/we_love/Application/Common/Conf/rsa_public_key.pem'; //linux服务器上的配置路径

        vendor('Alipay.Corefunction');
        vendor('Alipay.Notify');
        vendor('Alipay.Rsafunction');

    }


      /**
       * 签名字符串
       * @param $prestr 需要签名的字符串
       * return 签名结果
      */
     public  function rsaSign()
     {
     $prestr = I('post.data');
     $prestr = base64_decode($prestr);
     $public_key= file_get_contents($this->private_key);
     $pkeyid = openssl_get_privatekey($public_key);
     openssl_sign($prestr, $sign, $pkeyid);
     openssl_free_key($pkeyid);
     $sign = base64_encode($sign);
     $res = $this->rsaVerify($prestr,$sign);
     if(!empty($res))
     {
        $sign = urlencode($sign);
         $result['result'] = $sign;
         echo json_encode($result,JSON_UNESCAPED_UNICODE);
     }
     }


      /**
      * 验证签名
      * @param $prestr 需要签名的字符串
      * @param $sign 签名结果
      * return 签名结果
      */
    function rsaVerify($prestr, $sign)
     {
       $sign = base64_decode($sign);
       $public_key= file_get_contents($this->public_key);
       $pkeyid = openssl_get_publickey($public_key);
       if ($pkeyid)
       {
        $verify = openssl_verify($prestr, $sign, $pkeyid);
         openssl_free_key($pkeyid);
       }
     if($verify == 1)
     {
         return true;
      }else{
          return false;
            }
    }

    /*
 * 查询参数排序 a-z
 * */
    public function buildQuery( $query )
    {
        if ( !$query ) {
            return null;
        }

//将要 参数 排序
        ksort( $query );

        //重新组装参数
        $params = array();
        foreach($query as $key => $value){
            $params[] = $key .'='. $value ;
        }
        $data = implode('&', $params);

        return $data;

    }


    /******************************
    服务器异步通知页面方法
    其实这里就是将notify_url.php文件中的代码复制过来进行处理

     *******************************/
    function notifyurl(){
        /*
        同理去掉以下两句代码；
        */
        //require_once("alipay.config.php");
        //require_once("lib/alipay_notify.class.php");

        //这里还是通过C函数来读取配置项，赋值给$alipay_config
        $alipay_config=C('Alipay');
        var_dump($alipay_config);
        //计算得出通知验证结果
        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyNotify();
        if($verify_result) {
            //验证成功
            //获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
            $out_trade_no   = $_POST['out_trade_no'];      //商户订单号
            $trade_no       = $_POST['trade_no'];          //支付宝交易号
            $trade_status   = $_POST['trade_status'];      //交易状态
            $total_fee      = $_POST['total_fee'];         //交易金额
            $notify_id      = $_POST['notify_id'];         //通知校验ID。
            $notify_time    = $_POST['notify_time'];       //通知的发送时间。格式为yyyy-MM-dd HH:mm:ss。
            $buyer_email    = $_POST['buyer_email'];       //买家支付宝帐号；
            $parameter = array(
                "out_trade_no"     => $out_trade_no, //商户订单编号；
                "trade_no"     => $trade_no,     //支付宝交易号；
                "total_fee"     => $total_fee,    //交易金额；
                "trade_status"     => $trade_status, //交易状态
                "notify_id"     => $notify_id,    //通知校验ID。
                "notify_time"   => $notify_time,  //通知的发送时间。
                "buyer_email"   => $buyer_email,  //买家支付宝帐号；
            );
            if($_POST['trade_status'] == 'TRADE_FINISHED') {
                //
            }else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {                           if(!checkorderstatus($out_trade_no)){
                orderhandle($parameter);
                //进行订单处理，并传送从支付宝返回的参数；
            }
            }
            echo "success";        //请不要修改或删除
        }else {
            //验证失败
            echo "fail";
        }
    }

    public function notify_url()
    {
        $model = D('ceshi');
        if(empty($_POST))
        {
            $data = array(
                'ceshi'=>'回调失败',
                'time'=>date('Y-m-d H:i:s',time()),
            );
        }else{
            $out_trade_no   = $_POST['out_trade_no'];      //商户订单号
            $trade_no       = $_POST['trade_no'];          //支付宝交易号
            $trade_status   = $_POST['trade_status'];      //交易状态
            $total_fee      = $_POST['total_fee'];         //交易金额
            $notify_id      = $_POST['notify_id'];         //通知校验ID。
            $notify_time    = $_POST['notify_time'];       //通知的发送时间。格式为yyyy-MM-dd HH:mm:ss。
            $buyer_email    = $_POST['buyer_email'];       //买家支付宝帐号；
            $parameter = array(
                "out_trade_no"     => $out_trade_no, //商户订单编号；
                "trade_no"     => $trade_no,     //支付宝交易号；
                "total_fee"     => $total_fee,    //交易金额；
                "trade_status"     => $trade_status, //交易状态
                "notify_id"     => $notify_id,    //通知校验ID。
                "notify_time"   => $notify_time,  //通知的发送时间。
                "buyer_email"   => $buyer_email,  //买家支付宝帐号；
            );
            $data = array(
               'ceshi'=>json_encode($parameter),
                'time'=>date('Y-m-d H:i:s',time()),
            );
        }
        $model->data($data)->add();
        echo 'success';
    }

    /*
     * ios内购支付
     * @param array $data //客户端传来的订单信息
     * @param int $type //订单的支付类型，1.身份认证，2一月会员，3.三月会员，4.六个月会员，5一年会员
     * return json //支付的状态信息
     */
    public function ios_pay()
    {
        $model = D('pay_record');
        $user_id = I('post.user_id');
        $type = I('post.type');
        $user = new UserModel();
        $user->change_statu($user_id);
        $data = I('post.');
        $data['type'] = $type;
        $data['msg'] = 'success';
        $data['time'] = date('y-m-d H:i:s',time());
        $res = $model->data($data)->add();
        if(!empty($res))
        {
            $result = array(
                'msg'=>'success',
                'statu'=>1
            );
        }else{
            $result = array(
                'msg'=>'failed',
                'statu'=>2
            );
        }
        echo json_encode($result);
    }

    /*
     * 获取支付价格
     * @param array 对应优惠价格
     * @param int 1为获取认证费用 其余均为支付会员费用
     * @param boolean 查询优惠券，如果有自动使用并减免相关费用
     * @param json 返回优惠完之后的价格
     */
    public function get_pay_price()
    {
        //对应优惠价格表
        $price_array = array(
            '1'=>array(
                'reduce_price'=>10,
                'detail'=>'被邀请用户认证费减免',
            ),
            '2'=>array(
                'reduce_price'=>20,
                'detail'=>'一个月会员优惠券',
            ),
            '3'=>array(
                'reduce_price'=>30,
                'detail'=>'三个月会员优惠券',
            ),
            '4'=>array(
                'reduce_price'=>50,
                'detail'=>'六个月会员优惠券',
            ),
            '5'=>array(
                'reduce_price'=>80,
                'detail'=>'一年会员优惠券',
            ),
        );
        $model = new Model();
        $user_id = I('get.user_id');
        $type = I('get.type');
        if($type==1)
        {
            $sql = "select invite_code from wl_user where id=$user_id";
            $data = $model->query($sql);
            $invite_code = $data[0]['invite_code'];
            //查询支付的认证费用
            $auth = "select charge from wl_charge where type=$type";
            $auth_price = $model->query($auth);
            $price_auth = $auth_price[0]['charge'];
            if(!empty($invite_code))
            {
                $price = $price_auth-$price_array[1]['reduce_price'];

            }else{
                $price = $price_auth;
            }
            $Notify = new TicketModel();
            $count =$Notify->get_number();
            $result['number'] = $count;
        }else{
            //查询支付的会员费
            $asql = "select charge from wl_charge where type=$type";
            $data = $model->query($asql);
            $price = $data[0]['charge'];

            //查找是否有优惠券，有优惠券自动使用并减去抵扣价格
            $Notify = new TicketModel();
           $is_ticket = $Notify->search_ticket($user_id,$type);
            if(!empty($is_ticket))
            {
                $price = $price-$price_array[$type]['reduce_price'];
            }
            $result['reduce_price'] = $price_array[$type]['reduce_price'];
            $result['detail'] = $price_array[$type]['detail'];
        }
        $result['price'] = sprintf("%.2f", $price);
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    //显示会员费
    public function get_vip_price()
    {
        $model = M('charge');
        $data = $model->where('type!=1')->field('charge,type')->select();
        foreach($data as $key=>$value)
        {
            $data[$key]['charge']=sprintf('%.2f',$data[$key]['charge']);
        }
        echo json_encode($data);
    }

    //app提交支付宝提现请求
    public function draw_charge()
    {
        $model = M('draw');
        $data = I('post.');
        $data['draw_time'] = date('y-m-d H:i:s',time());
        $data['statu'] = 2;
        $res = $model->data($data)->add();
        if(!empty($res))
        {
            $result =array(
                'msg'=>'draw submit success!',
                'statu'=>1
            );
        }else{
            $result = array(
                'msg'=>'draw submit failed!',
                'statu'=>2
            );
        }
        echo json_encode($result);
    }

    //查看提现明细接口
    public function draw_list()
    {
        $model = M('draw');
        $user_id = I('get.user_id');
        $condition['user_id'] = $user_id;
        $data = $model->where($condition)->select();
        $sum = $model->where($condition)->sum('draw_amount');
        foreach($data as $key=>$value)
        {
            $data[$key]['sum'] = $sum;
        }
        echo json_encode($data);
    }




}